/**
 * Builder.cpp
 * Coyright (c) 2009 Xiaofeng Gu. All Rights Reserved.
 * Author : Xiaofeng Gu
 *
 * Creation Data : 2009/06/21
 */

#include "stdafx.h"
#include "Builder.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

HRESULT CBuilder::OnExecute()
{
	HRESULT hr = S_OK;
	hr = __super::OnExecute();
	if (hr != S_OK)
	{
		return hr;
	}

	CBuilderProcessCard* pBuilderProcessCard = GetBlockInfo<CBuilderProcessCard>(BUILDERPROCESSCARD);
	Families* pFamiles = pBuilderProcessCard->GetFamilies();
	for (Families::iterator itFa = pFamiles->begin(); itFa != pFamiles->end(); itFa ++)
	{
		CFamily* pFamily = *itFa;

		Knots* pKnots = pFamily->GetKnots();
		for (Knots::iterator it = pKnots->begin();
			it != pKnots->end(); it ++)
		{
			m_pKnot = *it;

			m_min[0] = 1000000000;
			m_min[1] = 1000000000;
			m_min[2] = 1000000000;
			m_max[0] = -1000000000;
			m_max[1] = -1000000000;
			m_max[2] = -1000000000;

			Build(m_pKnot->GetTopNode());

			m_pKnot->SetRange(
				CVec(m_min[0], m_min[1], m_min[2]),
				CVec(m_max[0], m_max[1], m_max[2]));
		}
	}
	

	return S_OK;
}

void CBuilder::Build(CTransNode* pNode)
{
	if (pNode == NULL) return;
	Nodes* pNodes = m_pKnot->GetNodes();
	pNodes->push_back(pNode);

	CBone* pBone = pNode->GetBone();


	if (m_min[0] > (*pBone)[0][0])
		m_min[0] = (*pBone)[0][0];
	if (m_min[1] > (*pBone)[0][1])
		m_min[1] = (*pBone)[0][1];
	if (m_min[2] > (*pBone)[0][2])
		m_min[2] = (*pBone)[0][2];
	if (m_max[0] < (*pBone)[0][0])
		m_max[0] = (*pBone)[0][0];
	if (m_max[1] < (*pBone)[0][1])
		m_max[1] = (*pBone)[0][1];
	if (m_max[2] < (*pBone)[0][2])
		m_max[2] = (*pBone)[0][2];

	if (m_min[0] > (*pBone)[1][0])
		m_min[0] = (*pBone)[1][0];
	if (m_min[1] > (*pBone)[1][1])
		m_min[1] = (*pBone)[1][1];
	if (m_min[2] > (*pBone)[1][2])
		m_min[2] = (*pBone)[1][2];
	if (m_max[0] < (*pBone)[1][0])
		m_max[0] = (*pBone)[1][0];
	if (m_max[1] < (*pBone)[1][1])
		m_max[1] = (*pBone)[1][1];
	if (m_max[2] < (*pBone)[1][2])
		m_max[2] = (*pBone)[1][2];

	Nodes* pChildren = pNode->GetChildren();
	for (int i = 0; i < (int)(pChildren->size()); i ++)
	{
		CTransNode* pChild = (*pChildren)[i];
		if (pChild != NULL)
		{
			Build(pChild);
		}
	}
}